
const dbConfig = require("./index")
const dayjs = require('dayjs')
const { Parameters } = require('../utils/utils')

/**
 * 获取工具函数
 * type=== all 获取所有
*/
const getToolFun = (req, res) => {
  const { type } = req.query
  let sql = ''
  let sqlArr = []
  if (type == 'all') {
    sql = `select * from tool.toolFunction`
  } else {
    sql = `select * from tool.toolFunction where userId=?`
    sqlArr = [req.userId]
  }

  dbConfig.sqlConnect(sql, sqlArr, (data, err) => {
    if (err) return res.sends('参数错误')
    res.sends(data)
  }, res)
}


//添加一条工具函数
const addToolFun = (req, res) => {
  const { keys, values, num } = new Parameters(req.body).add({ userId: req.userId, createTime: dayjs().format('YYYY-MM-DD') })
  const sql = `insert into tool.toolFunction(${keys}) values(${num})`

  dbConfig.sqlConnect(sql, [...values], (data, err) => {
    if (err) return res.sends(err)
    res.sends('成功')
  }, res)
}

/**删除一条*/
const delToolFun = (req, res) => {
  const sql = `delete from tool.toolFunction where id=?`
  dbConfig.sqlConnect(sql, [req.body.id], (data, err) => {
    if (err) return res.sends(err)
    res.sends('成功')
  }, res)
}

/**编辑一条*/
const editToolFun = (req, res) => {
  const { title, content, id } = req.body
  const sql = `update tool.toolFunction set title=?, content=? ,updateTime=?  where id=?`
  dbConfig.sqlConnect(sql, [title, content, dayjs().format('YYYY-MM-DD'), id], (data, err) => {
    if (err) return res.sends(err)
    res.sends('成功')
  }, res)
}

module.exports = { getToolFun, addToolFun, delToolFun, editToolFun }
